<template>
    <div>
        <!-- 播放器容器 -->
        <div playsrc="playsrc" ref="playerContainer" class="player-container"></div>
        <!-- 提示信息 -->
        <div v-if="message" class="message">{{ message }}</div>
    </div>
</template>

<script>
import Player from "nplayer";
import Hls from "hls.js";

export default {
    name: "HlsPlayer",
    props: {
        playsrc:{
            type: String,
            default: ''
        }
    },
    data() {
        return {
            player: null, // NPlayer 实例
            message: "", // 提示信息
            limitTime: 3, // 限制播放时间（单位：秒）
        };
    },
    created() {
    },
    mounted() {
        this.initPlayer(this.playsrc);
    },
    methods: {
        initPlayer(playsrc) {
            // 创建 video 元素
            const videoElement = document.createElement("video");
            this.$refs.playerContainer.appendChild(videoElement);

            // 初始化 HLS
            if (Hls.isSupported()) {
                const hls = new Hls();
                hls.loadSource(playsrc); // 替换为你的 HLS 流地址
                hls.attachMedia(videoElement);
                hls.on(Hls.Events.MANIFEST_PARSED, () => {
                    this.setupPlayer(videoElement);
                });
            } else if (
                videoElement.canPlayType("application/vnd.apple.mpegurl")
            ) {
                // 如果浏览器原生支持 HLS（如 Safari）
                videoElement.src = playsrc; // 替换为你的 HLS 流地址
                videoElement.addEventListener("loadedmetadata", () => {
                    this.setupPlayer(videoElement);
                });
            }
        },
        setupPlayer(videoElement) {
            // 初始化 NPlayer
            this.player = new Player({
                video: videoElement,
            });
            this.player.mount(this.$refs.playerContainer);

            // 监听播放事件
            videoElement.addEventListener("play", this.onPlay);
            videoElement.addEventListener("timeupdate", this.onTimeUpdate);
        },
        onPlay() {
            this.message = "视频开始播放";
        },
        onTimeUpdate() {
            const currentTime = this.player.video.currentTime;
            if (currentTime >= this.limitTime) {
                this.player.video.pause(); // 暂停视频
                this.message = `视频已播放 ${this.limitTime} 秒，播放结束`;
                this.player.video.removeEventListener("timeupdate", this.onTimeUpdate); // 移除监听
            }
        },
    },
    beforeDestroy() {
        if (this.player) {
            this.player.destroy();
        }
    },
};
</script>

<style scoped>
.player-container {
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
}
.message {
    margin-top: 10px;
    font-size: 16px;
    color: #333;
    text-align: center;
}
</style>
